<script setup lang="ts">
import { reactive, ref, unref, onBeforeMount } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElTable } from 'element-plus'
import Drawer from './components/Drawer.vue'
import SetupPassword from './components/SetupPassword.vue'
import { userListApi, deleteUserApi, frozenUserApi, exportApi } from '@/api/userManage/index'
import type { paramsType, recordsType, resultType } from '@/api/userManage/types'
import { uploadExcelApi } from '@/api/common/import'
import { ElMessage, ElMessageBox } from 'element-plus'

const loading = ref(true)

const formRef = ref<FormInstance>()
// 展开/折叠 状态定义
const switchFolderStatus = ref(false)

// 性别编码
enum sexCodes {
  male = 1, //男
  female = 2 //女
}
// 状态编码
enum statusCodes {
  normal = 1, //正常
  freeze = 2 //冻结
}
// 性别下拉
const sexOptions = [
  { label: '男', value: sexCodes.male },
  { label: '女', value: sexCodes.female }
]
// 状态下拉
const statusOptions = [
  { label: '正常', value: statusCodes.normal },
  { label: '冻结', value: statusCodes.freeze }
]
// 表单字段定义
const formInline = reactive({
  username: '',
  sex: '',
  realname: '',
  phone: '',
  status: ''
})

/***********************表单处理********************** */
const switchFolder = () => {
  switchFolderStatus.value = !switchFolderStatus.value
}
// 查询表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  let params = {
    ...formInline,
    pageNo: pagination.pageNo,
    pageSize: pagination.pageSize
  }
  getUserList(params)
}
// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  getUserList({
    pageNo: pagination.pageNo,
    pageSize: pagination.pageSize
  })
  formEl.resetFields()
}
/*************************table处理***************************** */

let tableData = ref<Array<recordsType>>([])

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<[]>([])
const toggleSelection = (rows?: []) => {
  if (rows) {
    rows.forEach((row) => {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      multipleTableRef.value!.toggleRowSelection(row, undefined)
    })
  } else {
    multipleTableRef.value!.clearSelection()
  }
}
const handleSelectionChange = (val: []) => {
  multipleSelection.value = val
}
// 添加用户信息
const addUser = () => {
  drawerType.value = 1
  ruleFormProps.value = null
  drawerTitle.value = '新增'
  drawer.value = true
}
// 编辑用户信息
const editUser = (params: recordsType) => {
  drawerType.value = 2
  ruleFormProps.value = params
  drawerTitle.value = '编辑'
  drawer.value = true
}
const pwdVisible = ref(false)
const passwordProps = ref()
const setPassword = (params: recordsType) => {
  passwordProps.value = params
  pwdVisible.value = true
}
// 详情用户信息
const detailUser = (params: recordsType) => {
  drawerType.value = 3
  ruleFormProps.value = params
  drawerTitle.value = '详情'
  drawer.value = true
}
// 删除用户
const deleteUser = (params: recordsType) => {
  ElMessageBox.confirm('确定要删除当前用户吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let { id = '' } = params
      let rst = await deleteUserApi(id)
      let { code, success } = rst
      if (code == 200 && success) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
        refreshUserList()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}
// 冻结、解冻用户
const frozenUser = (params: recordsType) => {
  let msg = params.status == 1 ? '冻结' : '解冻'
  ElMessageBox.confirm(`确定要${msg}当前用户吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let ids = params.id
      let status = params.status == 1 ? 2 : 1

      let rst = await frozenUserApi(ids, status)
      let { code, success } = rst
      if (code == 200 && success) {
        ElMessage({
          type: 'success',
          message: '冻结成功'
        })
        refreshUserList()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

// 导出
const exportData = async () => {
  let rst = await exportApi({
    ...formInline,
    pageNo: pagination.pageNo,
    pageSize: pagination.pageSize
  })
  var down = document.createElement('a')
  down.href = 'http://192.168.10.3:9001/public-opinion/'+rst.result
  down.click()
  down.remove()
}
// 导入
const importData = async ({ file }) => {
  let rst = await uploadExcelApi(file, '/sys/user/importExcel')
  let { data } = rst
  if (data.code == 200 && data.success) {
    ElMessage.success('文件上传成功')
  } else {
    ElMessage.error(`文件上传失败，${data.message}`)
  }
}

/**************************分页**************************** */
let pagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
})
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  getUserList({
    ...formInline,
    pageNo: pagination.pageNo,
    pageSize: pagination.pageSize
  })
}
const handleCurrentChange = (val: number) => {
  pagination.pageNo = val
  getUserList({
    ...formInline,
    pageNo: pagination.pageNo,
    pageSize: pagination.pageSize
  })
}
/****************************抽屉******************************* */
const drawer = ref(false)
const drawerType = ref<Number>(1)
const ruleFormProps = ref()
const drawerTitle = ref('')
const updateDrawerStatus = (val: boolean) => {
  drawer.value = val
}
/*****************************请求事件************************************ */
// 删除、添加用户成功后的回调
const refreshUserList = () => {
  getUserList({
    ...formInline,
    pageNo: pagination.pageNo,
    pageSize: pagination.pageSize
  })
}
const getUserList = async (params) => {
  let rst = await userListApi(params)
  let {
    result: { total = 0, current = 1, size = 10, records = [] }
  } = rst
  loading.value = false
  pagination.pageNo = current
  pagination.pageSize = size
  pagination.total = total
  tableData.value = records
}
onBeforeMount(() => {
  getUserList({
    pageNo: pagination.pageNo,
    pageSize: pagination.pageSize
  })
})
</script>

<template>
  <div class="user-manage">
    <!-- 表单部分 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline" ref="formRef">
      <el-form-item label="账号：" prop="username">
        <el-input v-model="formInline.username" />
      </el-form-item>
      <el-form-item label="性别：" prop="sex">
        <el-select v-model="formInline.sex">
          <el-option
            :label="item.label"
            :value="item.value"
            :key="index"
            v-for="(item, index) in sexOptions"
          />
        </el-select>
      </el-form-item>

      <template v-if="switchFolderStatus">
        <el-form-item label="真实名字：" prop="realname">
          <el-input v-model="formInline.realname" />
        </el-form-item>
        <el-form-item label="手机号码：" prop="phone">
          <el-input v-model="formInline.phone" />
        </el-form-item>
        <el-form-item label="用户状态：" prop="status">
          <el-select v-model="formInline.status">
            <el-option
              :label="item.label"
              :value="item.value"
              :key="index"
              v-for="(item, index) in statusOptions"
            />
          </el-select>
        </el-form-item>
      </template>

      <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)">
          <el-icon style="vertical-align: middle">
            <Search />
          </el-icon>
          <span style="vertical-align: middle">查询</span>
        </el-button>
        <el-button type="primary" @click="resetForm(formRef)">
          <el-icon style="vertical-align: middle"><RefreshRight /></el-icon>
          <span style="vertical-align: middle">重置</span>
        </el-button>
        <el-button link @click="switchFolder">
          <span style="vertical-align: middle; color: #1890ff">{{
            switchFolderStatus ? '收起' : '展开'
          }}</span>
          <el-icon
            style="vertical-align: middle; color: #1890ff"
            :style="{ transform: switchFolderStatus ? 'rotateZ(180deg)' : 'rotateZ(0deg)' }"
            ><ArrowDown
          /></el-icon>
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 功能按钮部分 -->
    <div class="btn-group">
      <!-- 添加用户 -->
      <el-button type="primary" @click="addUser">
        <el-icon style="vertical-align: middle; color: #fff">
          <Plus />
        </el-icon>
        <span style="vertical-align: middle">添加用户</span>
      </el-button>
      <!-- 导出 -->
      <el-button type="primary" @click="exportData">
        <!-- <el-icon style="vertical-align: middle; color: #fff">
          <Download />
        </el-icon> -->
        <Icon icon="uil:export" color="white" />
        <span style="vertical-align: middle">导出</span>
      </el-button>
      <!-- 导入 -->
      <el-upload
        style="display: inline-block; vertical-align: middle; margin-left: 12px"
        :http-request="importData"
        :show-file-list="false"
      >
        <el-button type="primary">
          <!-- <el-icon style="vertical-align: middle; color: #fff">
            <Upload />
          </el-icon> -->
          <Icon icon="mdi:import" color="white" />
          <span style="vertical-align: middle">导入</span>
        </el-button>
      </el-upload>
    </div>
    <!-- 表格多选——清空 -->
    <!-- <div class="table-clear">
      <span
        >已选择
        <span style="color: #1890ff; margin-right: 3px; font-weight: bolder">{{
          multipleSelection.length
        }}</span
        >项
      </span>
      <el-button link @click="toggleSelection()">
        <span style="vertical-align: middle; color: #1890ff">清空</span>
      </el-button>
    </div> -->
    <!-- table表格部分 -->
    <el-table
      ref="multipleTableRef"
      :data="tableData"
      style="width: 100%"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" /> -->
      <el-table-column label="用户账号" width="120">
        <template #default="scope">{{ scope.row.username }}</template>
      </el-table-column>
      <el-table-column property="realname" label="用户姓名" width="120" />
      <el-table-column property="avatar" label="头像" show-overflow-tooltip>
        <template #default="scope">
          <img
            v-if="scope.row.avatar"
            :src="scope.row.avatar"
            alt=""
            style="width: 40px; height: 40px; border-radius: 4px"
          />
          <el-icon v-else style="font-size: 33px"><Avatar /></el-icon>
        </template>
      </el-table-column>

      <el-table-column property="sex" label="性别" show-overflow-tooltip>
        <template #default="scope">
          <span v-if="scope.row.sex == 1">男</span>
          <span v-else-if="scope.row.sex == 2">女</span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column property="birthday" label="生日" show-overflow-tooltip />
      <el-table-column property="phone" label="手机号码" show-overflow-tooltip />
      <el-table-column property="workNo" label="工号" show-overflow-tooltip />
      <el-table-column property="orgCodeTxt" label="部门" show-overflow-tooltip />
      <el-table-column property="statusText" label="状态" show-overflow-tooltip />
      <el-table-column property="操作" label="操作">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="editUser(scope.row)">编辑</el-button>
          <el-dropdown trigger="click" style="vertical-align: middle">
            <el-button link type="primary">
              <span style="font-size: 12px">更多</span>
              <el-icon style="vertical-align: middle; color: #1890ff"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="detailUser(scope.row)">详情</el-dropdown-item>
                <el-dropdown-item @click="setPassword(scope.row)">密码</el-dropdown-item>
                <el-dropdown-item @click="deleteUser(scope.row)">删除</el-dropdown-item>
                <el-dropdown-item @click="frozenUser(scope.row)">
                  {{ scope.row.status == 1 ? '冻结' : '解冻' }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pagination.pageNo"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 30, 50, 100]"
      :small="false"
      :disabled="false"
      :background="false"
      layout="total, sizes, prev, pager, next"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 10px; display: flex; justify-content: center"
    />
  </div>
  <Drawer
    v-if="drawer"
    :drawerType="drawerType"
    :drawer="drawer"
    :title="drawerTitle"
    :rule-form-props="ruleFormProps"
    @update-drawer="updateDrawerStatus"
    @update-user-list="refreshUserList"
  />
  <SetupPassword
    v-if="pwdVisible"
    :visible="pwdVisible"
    :pwd-props="passwordProps"
    @update-visible="pwdVisible = false"
  />
</template>
<style lang="less" scoped>
.user-manage {
  // 表单部分
  .el-form {
    .el-form-item {
      width: 23.5%;
      margin-right: 20px;
      .el-form-item__content {
        width: 100%;
        .el-select {
          width: 100%;
        }
      }
    }
  }
  // btn-group部分
  .btn-group {
    margin-bottom: 16px;
  }
  // table-clear部分
  .table-clear {
    padding-bottom: 8px;
    padding-top: 8px;
    padding-left: 37px;
    padding-right: 15px;
    margin-bottom: 16px;
    border: 1px solid #91d5ff;
    background-color: #e6f7ff;
    border-radius: 4px;
    font-size: 14px;

    span {
      color: rgba(0, 0, 0, 0.65);
      margin-right: 35px;
    }
  }
}
</style>
